package o2o.service.order.other;

import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinyou.utils.common.*;
import lombok.extern.slf4j.Slf4j;
import map.HttpRequest;
import o2o.cache.agent.AgentOrderOverTimeMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.order.OrderPolicyRecordMemory;
import o2o.cache.order.OrderStatusMemory;
import o2o.cache.order.OtherOrderMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserAddressRecordMemory;
import o2o.company.model.ShopInfo;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.OrderOverTimeInfo;
import o2o.dao.PO.order.*;
import o2o.dao.PO.policy.INSURANCE_STATUS;
import o2o.dao.PO.policy.PolicyInfo;
import o2o.dao.PO.user.UserAddressRecord;
import o2o.dao.PO.wallet.PAY_TYPE;
import o2o.dao.TO.policy.InsuredsDto;
import o2o.dao.TO.policy.PolicyDto;
import o2o.dao.TO.policy.PolicyOrderDto;
import o2o.dao.VO.agent.CityAgentVO;
import o2o.dao.VO.order.OtherOrderInfoExcel;
import o2o.dao.VO.order.OtherOrderInfoVO;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.thridpost.dada.controller.DadaCityController;
import o2o.thridpost.dada.controller.DadaOrderController;
import o2o.thridpost.dada.model.to.AddDadaOrderTO;
import o2o.utils.OrderUtils;
import o2o.web.actions.agent.CityAgentMan;
import o2o.web.actions.order.SubmitOrderMan;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 其他订单相关操作
 */
@Service
@Slf4j
public class OtherOrderService {
    @Autowired
    private DadaCityController dadaCityController;
    @Autowired
    private DadaOrderController dadaOrderController;

    /**
     * 读取批量的订单信息
     *
     * @param info
     * @return
     */
    public List<OtherOrderInfoVO> readExcelFileV2(MultipartFile info, String username) throws Exception {
        if (info == null) {
            return Collections.emptyList();
        }
        List<OtherOrderInfoExcel> orderExcelList = null;
        try (InputStream inputStream = info.getInputStream()) {
            ImportParams params = new ImportParams();
            params.setTitleRows(1); // 设置标题行数
            params.setHeadRows(1); // 设置字符行数
            orderExcelList = JYEasyExcelUtils.importExcel(inputStream, 0, 1, 1, OtherOrderInfoExcel.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        if (!ValidateUtil.isAbsList(orderExcelList)) {
            return Collections.emptyList();
        }
        return orderExcelList.stream().map(item -> {
            OtherOrderInfoVO vo = new OtherOrderInfoVO();
            BeanUtils.copyProperties(item, vo);
            vo.setUsername(username);
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 批量导入跑腿订单
     *
     * @param json
     * @param opUser
     */
    public void batchPaotuiOrder(String fromAddress, Double fromLat, Double fromLng,
                                 String fromProvince,
                                 String fromCity,
                                 String fromCounty,
                                 String fromUser,
                                 String fromPhone, String json, String opUser) throws Exception {
        List<OtherOrderInfoVO> orderInfoVOList = JSONArray.parseArray(json, OtherOrderInfoVO.class);
        if (!ValidateUtil.isAbsList(orderInfoVOList)) {
            return;
        }
        /*validOtherOrderInfoList(orderInfoVOList, fromAddress, fromLat, fromLng,
                fromProvince,
                fromCity,
                fromCounty,
                fromUser,
                fromPhone, opUser);*/
        Connection conn = null;

        Long createTime = DateUtils.getCurrTime();
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
            // 导入
            batchInsertIntoOrder(orderInfoVOList, conn, opUser, createTime, null);
            conn.commit();
        } catch (Exception e) {
            e.getMessage();
            UserDaoSql.getInstance().rollback(conn);
            throw e;
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        // 缓存
        OrderInfoMemory.getInstance().create(createTime);
        OtherOrderMemory.getInstance().create(createTime);
        OrderStatusMemory.getInstance().create(createTime);

    }


    /**
     * 查看数据是否符合要求
     *
     * @param list
     * @throws Exception
     */
    private void validOtherOrderInfoList(List<OtherOrderInfoVO> list, String fromAddress, Double fromLat, Double fromLng,
                                         String fromProvince,
                                         String fromCity,
                                         String fromCounty,
                                         String fromUser,
                                         String fromPhone, String username) throws Exception {
        //根据发货地址 查找最近的代理
        if (ValidateUtil.isNull(fromCity) || ValidateUtil.isNotLatLng(fromLat, fromLng)) {
            throw new Exception("未获取到店铺经纬度信息");
        }
        CityAgentVO cityAgentVO = CityAgentMan.getCityAgent(fromCity, fromLat, fromLng);
        if (null == cityAgentVO) {
            throw new Exception("当前位置未开通跑腿");
        }
        // 订单信息
        int index = 0;
        for (OtherOrderInfoVO vo : list) {
            index++;
            if (ValidateUtil.isNull(vo.getToUser()) || ValidateUtil.isNull(vo.getToPhone()) || ValidateUtil.isNull(vo.getToCity()) || ValidateUtil.isNull(vo.getToAddress())
                    || ValidateUtil.isNotLatLng(vo.getToLat(), vo.getToLng())) {
                throw new Exception("第" + index + "条订单信息不全,导入失败");
            }
            if (ValidateUtil.isNotAbsDouble(vo.getTotalWeight())) {
                vo.setTotalWeight(0.0d);
            }
            if (ValidateUtil.isNotAbsDouble(vo.getDeliveryPrice())) {
                vo.setDeliveryPrice(0.0d);
            }
            if (ValidateUtil.isNotAbsDouble(vo.getGoodsPrice())) {
                vo.setGoodsPrice(0.0d);
            }
            if (ValidateUtil.isNotAbsDouble(vo.getTotalMoney())) {
                vo.setTotalMoney(vo.getGoodsPrice());
            }
            if (ValidateUtil.isNotAbsDouble(vo.getXiaofei())) {
                vo.setXiaofei(0.0d);
            }
            if (ValidateUtil.isNotAbsDouble(vo.getYunfeixianPrice())) {
                vo.setYunfeixianPrice(0.0d);
            }
            if (ValidateUtil.isNull(vo.getGoodsType())) {
                vo.setGoodsType("商品");
            }
            if (ValidateUtil.isNull(vo.getGoods())) {
                vo.setGoodsType("商品");
            }
            if (ValidateUtil.isNull(vo.getToProvince()) && ValidateUtil.isNull(vo.getToCity()) && ValidateUtil.isNull(vo.getToCounty())) {
                vo.setToProvince(fromProvince);
                vo.setToCity(fromCity);
                vo.setToCounty(fromCounty);
            }

            // form
            vo.setFromAddress(fromAddress)
                    .setFromUser(fromUser)
                    .setFromPhone(fromPhone)
                    .setFromProvince(fromProvince)
                    .setFromCity(fromCity)
                    .setFromCounty(fromCounty)
                    .setFromLat(fromLat)
                    .setFromLng(fromLng)
                    .setType(OtherOrderInfo.PAO_TUI);
            vo.setUsername(username);
            Double distance = Geohash.distance(vo.getFromLat(), vo.getFromLng(), vo.getToLat(), vo.getToLng());
            distance = JYMathDoubleUtils.scaleHalfUp(JYMathDoubleUtils.div(distance, 1000));
            vo.setDistance(distance);
            vo.setAgentId(cityAgentVO.getId());
        }
    }

    public void insertIntoPoatuiOrder(OtherOrderInfoVO to, String opUser, Long createTime, Long shopId) throws Exception {
        List<OtherOrderInfoVO> list = new ArrayList<>();
        list.add(to);
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
            // 导入
            batchInsertIntoOrder(list, conn, opUser, createTime, shopId);
            conn.commit();
        } catch (Exception e) {
            e.getMessage();
            UserDaoSql.getInstance().rollback(conn);
            throw e;
        } finally {
            UserDaoSql.getInstance().close(conn);
        }

        // 缓存
        OrderInfoMemory.getInstance().create(createTime);
        OtherOrderMemory.getInstance().create(createTime);
        OrderStatusMemory.getInstance().create(createTime);
    }

    /**
     * 批量导入到订单中
     *
     * @param list
     * @param opUser
     * @param createTime
     */
    private void batchInsertIntoOrder(List<OtherOrderInfoVO> list, Connection con, String opUser, Long createTime, Long shopId) throws Exception {
        boolean isShopPaotui = false;
        /*if (SYS_SETTINGS.IS_SHOP_PAOTUI == 1) {
            isShopPaotui = true;
        }*/
        Integer orders_status = ORDER_STATUS.PAYED;
        if (isShopPaotui) {
            orders_status = ORDER_STATUS.OVER;
        }

        for (OtherOrderInfoVO vo : list) {
            OtherOrderInfo otherOrderInfo = new OtherOrderInfo();
            BeanUtils.copyProperties(vo, otherOrderInfo);
            otherOrderInfo.setDelFlag(0);
            otherOrderInfo.setCreateUser(opUser);
            otherOrderInfo.setCreateTime(createTime);
            otherOrderInfo.setPickUpTime(0L);
            String orderNo = null;
            if (StringUtils.isNotEmpty(vo.getOrderNo()) && (vo.getOrderNo().endsWith("oth") || vo.getOrderNo().endsWith("mt") || vo.getOrderNo().endsWith("elm"))) {
                orderNo = vo.getOrderNo();
            } else {
                orderNo = OrderUtils.getOrderNo();
            }

            otherOrderInfo.setOrderNo(orderNo);
            otherOrderInfo.setPaySign(null);
            otherOrderInfo.setPayTime(orders_status == ORDER_STATUS.PAYED ? createTime : null);
            otherOrderInfo.setPayType(orders_status == ORDER_STATUS.PAYED ? PAY_TYPE.UNDERLINE : null);
            otherOrderInfo.setOrderStatus(orders_status);
            UserDaoSql.getInstance().saveObj(PojoTables.OTHER_ORDER_INFO, otherOrderInfo, con);


            Double totalMoney = otherOrderInfo.getTotalMoney();
            Double mustPayMoney = totalMoney;
            Double awardMoney = 0.0d;
            Double platformAwardMoney = 0.0d;
            Double shopAwardMoney = 0.0d;

            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderStatus(orders_status);
            if (isShopPaotui) {
                orderInfo.setIsShopPaoTuiOrder(1);
                orderInfo.setIsArrivePay(1);
                orderInfo.setPayType(PAY_TYPE.UNDERLINE).setPayTime(DateUtils.getCurrTime());
            }
            if (StringUtils.isNotEmpty(vo.getDeliveryCallBack())) {
                orderInfo.setDeliveryCallBack(vo.getDeliveryCallBack());
            }
            if (vo.getPreDayNo() != null) {
                orderInfo.setPreDayNo(vo.getPreDayNo());
            }
            if (StringUtils.isNotEmpty(vo.getDeliveryPlateOrderNo())) {
                orderInfo.setDeliveryPlateOrderNo(vo.getDeliveryPlateOrderNo());
            }
            orderInfo.setOrderType(ORDER_TYPE.PAO_TUI); // 订单类型，跑腿订单
            orderInfo.setOrderNo(orderNo);
            orderInfo.setCreateTime(createTime);
            orderInfo.setCreateUser(opUser);
            orderInfo.setDelFlag(0);
            orderInfo.setTotalPrice(mustPayMoney);
            orderInfo.setAgentId(vo.getAgentId());
            //
            orderInfo.setAwardMoney(awardMoney);
            orderInfo.setShopAwardMoney(shopAwardMoney);
            orderInfo.setPlatformAwardMoney(platformAwardMoney);
            //

//        orderInfo.setTotalPrice(info.getTotalMoney());
            orderInfo.setTotalMoney(totalMoney);
            orderInfo.setTipMoney(otherOrderInfo.getXiaofei());
            orderInfo.setDeliveryPrice(otherOrderInfo.getDeliveryPrice());
            orderInfo.setUsername(otherOrderInfo.getUsername());
            orderInfo.setCity(otherOrderInfo.getToCity());
            orderInfo.setProvince(otherOrderInfo.getToProvince());
            orderInfo.setCounty(otherOrderInfo.getToCounty());
            orderInfo.setLat(otherOrderInfo.getToLat());
            orderInfo.setLng(otherOrderInfo.getToLng());
            orderInfo.setDeliveryId(otherOrderInfo.getId());
            orderInfo.setBuyer(otherOrderInfo.getToUser());
            orderInfo.setTelephone(otherOrderInfo.getToPhone());
            orderInfo.setAddress(otherOrderInfo.getToAddress());
            orderInfo.setTotalWeight(otherOrderInfo.getTotalWeight());
            orderInfo.setDistance(vo.getDistance());
            orderInfo.setShopAddress(otherOrderInfo.getFromAddress());
            orderInfo.setShopLat(otherOrderInfo.getFromLat());
            orderInfo.setShopLng(otherOrderInfo.getFromLng());
            orderInfo.setShopName(otherOrderInfo.getFromUser());
            orderInfo.setShopCity(otherOrderInfo.getFromCity());
            orderInfo.setShopPhone(otherOrderInfo.getFromPhone());
            orderInfo.setIsZiQu(0);
            orderInfo.setCarTipId(otherOrderInfo.getCarTipId());
            orderInfo.setShopId(shopId == null ? -2 : shopId);
            orderInfo.setZiQuTime(otherOrderInfo.getPickUpTime());
            orderInfo.setIsComment(0);//是否已评价
            orderInfo.setUserDel(0);//是否已删除 0未删，1删除
            orderInfo.setIsUrgent(0);//是否加急
            orderInfo.setNote(otherOrderInfo.getNote());//订单备注
            orderInfo.setOrderDeliveryTime(vo.getOrderDeliveryTime());//订单预计配送时间
            orderInfo.setSorts(vo.getSorts()); // 平台订单号（#12）

            ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(orderInfo.getUsername());
            if (shopInfo == null) {
                shopInfo = ShopMemory.getInstance().getShopById(shopId);
            }

            boolean isThirdPart = false;
            // 1为开启第三方配送
            if (shopInfo != null && "1".equals(shopInfo.getThirdPartyType())) {
                // 达到多少公里
                String thirdPartyCond = shopInfo.getThirdPartyCond();
                // 第三方配送
                String thirdParty = shopInfo.getThirdParty();
                // 计算商家与买家的距离
                double distance = vo.getDistance();
                // 如果大于, 甩给第三方配送
                if (distance > Integer.parseInt(thirdPartyCond) * 1000) {
                    switch (thirdParty.toLowerCase()) {
                        case "dada":
                            log.info("满足第三方配送条件, 将把订单转发给达达配送, 订单号:{}", orderInfo.getOrderNo());
                            // 可以接单的配送公司
                            orderInfo.setOther_post_code("dada");
                            // 推送到第三方
                            orderInfo.setIsOtherPost(1);
                            // 查询城市代码
                            String cityResult = dadaCityController.queryCityCode(orderInfo.getCity());
                            JSONObject resultObj = JSONObject.parseObject(cityResult);
                            if (StringUtils.isNotEmpty(resultObj.getString("error"))) {
                                orderInfo.setOtherPostState(-1);
                                log.error("获取达达城市代码错误, city:{}", orderInfo.getCity());
                            } else {
                                String cityCode = resultObj.getJSONObject("info").getString("city_code");
                                log.error("获取达达城市代码:{}", cityCode);
                                // 添加达达订单
                                AddDadaOrderTO addDadaOrderTO = new AddDadaOrderTO(orderInfo, shopInfo, cityCode);
                                String orderResult = dadaOrderController.addOrderToDada(addDadaOrderTO);
                                JSONObject orderResultJson = JSONObject.parseObject(orderResult);
                                int status = orderResultJson.getInteger("status");
                                if (status == 0) {
                                    log.error("添加达达订单失败, 原因:{}", orderResultJson.getString("error"));
                                    orderInfo.setOtherPostState(-1);
                                    throw new Exception("添加达达订单失败, 原因:" + orderResultJson.getString("error"));
                                } else {
                                    orderInfo.setOtherPostState(1);
                                    // 是否已同步给第三方 0未同步 1已同步
                                    orderInfo.setIsSync2Tri(1);
                                    // 是否取消或退款已同步给第三方 0未同步 1已同步
                                    orderInfo.setIsRefundSync2Tri(0);
                                    isThirdPart = true;
                                }
                            }
                            break;
                    }
                }
            }
            // 如果是第三方配送不需要这些
            if (!isThirdPart) {
                if (shopInfo != null) {
                    if (StringUtils.isNotEmpty(shopInfo.getBaseHour()) && StringUtils.isNotEmpty(shopInfo.getPeakHour())) {
                        String baseHour = shopInfo.getBaseHour();
                        String peakHour = shopInfo.getPeakHour();
                        String peakTimeBucket = shopInfo.getPeakTimeBucket();
                        // 计算骑手配送时长
                        int postmanOverTime = Integer.parseInt(StringUtils.isEmpty(baseHour) ? "0" : baseHour);
                        if (StringUtils.isNotEmpty(peakTimeBucket)) {
                            JSONArray jsonArray = JSONObject.parseArray(peakTimeBucket);
                            SimpleDateFormat df = new SimpleDateFormat("HH:mm");
                            String now = df.format(new Date());
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONArray array = jsonArray.getJSONArray(i);
                                if (DateUtils.isInTimeScope(now, array.getString(0), array.getString(1))) {
                                    postmanOverTime += Integer.parseInt(StringUtils.isEmpty(peakHour) ? "0" : peakHour);
                                    break;
                                }
                            }
                        }
                        // 设置骑手配送时长
                        orderInfo.setAgentPostmanOverTime(postmanOverTime);
                        // 设置订单即将超时提醒
                        orderInfo.setAlertOrderTime(Integer.parseInt(shopInfo.getTimeoutRemind()));
                    } else {
                        // 配送时长问题
                        OrderOverTimeInfo agentOrderOverTimeInfo = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(orderInfo.getAgentId());
                        if (null == agentOrderOverTimeInfo) {
                            agentOrderOverTimeInfo = AgentOrderOverTimeMemory.getInstance().getPlateDefaultSetting();
                        }
                        if (null != agentOrderOverTimeInfo) {
                            orderInfo.setAgentPostmanOverTime(agentOrderOverTimeInfo.getPostmanOverTime());
                            orderInfo.setAlertOrderTime(agentOrderOverTimeInfo.getAlertOrderTime());
                        }
                    }
                }
                // 订单超时设置 9
                if (ValidateUtil.isID(orderInfo.getAgentId()) && SYS_SETTINGS.HAS_PAOTUI_ORDER_TIME_SET == 1) {
                    // 配送时长问题
                    OrderOverTimeInfo agentOrderOverTimeInfo = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(orderInfo.getAgentId());
                    if (null == agentOrderOverTimeInfo) {
                        agentOrderOverTimeInfo = AgentOrderOverTimeMemory.getInstance().getPlateDefaultSetting();
                    }
                    if (null != agentOrderOverTimeInfo) {
                        Double distance = orderInfo.getDistance();
                        if (ValidateUtil.isAbsDouble(distance)) {
                            distance = 0.0d;
                        }
                        orderInfo.setAgentOrderOverTime(SubmitOrderMan.calculateOrderPsTime(agentOrderOverTimeInfo, distance));
                        orderInfo.setAgentNotTakenOrderTime(agentOrderOverTimeInfo.getNotTakenOrderTime());
                        orderInfo.setAgentPostmanAdvanceTime(agentOrderOverTimeInfo.getPostmanAdvanceTime());
                        orderInfo.setAlertPostmanTime(agentOrderOverTimeInfo.getAlertPostmanTime());
                        orderInfo.setPostmanBackOrderTime(agentOrderOverTimeInfo.getPostmanBackOrderTime());
                    }
                }
            }

            UserDaoSql.getInstance().saveObj(PojoTables.OrderInfo, orderInfo, con);
            //添加订单下各个商品信息
            if (vo.getGoodsList() != null && vo.getGoodsList().size() != 0) {
                for (OrderInfoGoods orderGoods : vo.getGoodsList()) {
                    OrderItems items = new OrderItems();
                    BeanUtils.copyProperties(orderGoods, items);
                    items.setTotalCount(orderGoods.getTotalCount().intValue());
                    items.setOrderNo(orderInfo.getOrderNo());
                    items.setTotalMoney(orderGoods.getTotalPrice());
                    items.setCreateTime(createTime);
                    items.setCreateUser(opUser);
                    items.setPrice(orderGoods.getTotalPrice() / orderGoods.getTotalCount());
                    UserDaoSql.getInstance().saveObj(PojoTables.ORDER_ITEMS, items, con);
                }
            }

            //4. 订单状态保存
            OrderStatus orderStatus = new OrderStatus();
            orderStatus.setOrderNo(orderNo);
            orderStatus.setCreateUser(opUser);
            orderStatus.setCreateTime(createTime);
            orderStatus.setOrderStatus(orders_status);
            UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, orderStatus, con);
        }

    }


    // 发送保单信息
    public void sendThreadPolicy(List<PolicyInfo> policyInfos, String orderNo, String opUser) {
        // 1. 发送保单信息 并修改本地的数据库
        for (PolicyInfo info : policyInfos) {
            List<InsuredsDto> insuredsDtoList = new ArrayList<>();
            // 发送的保单信息
            PolicyDto policyDto = new PolicyDto();
            PolicyOrderDto orderDto = new PolicyOrderDto();
            BeanUtils.copyProperties(info, orderDto);
            orderDto.setOrderNo(info.getOrderNoIndex());
            policyDto.setOrder(orderDto);
            InsuredsDto insuredsDto = new InsuredsDto();
            BeanUtils.copyProperties(info, insuredsDto);
            insuredsDtoList.add(insuredsDto);
            policyDto.setInsureds(insuredsDtoList);
            String url = SYS_CONFIG_PATH.BAO_XIAN_SERVICE_URL + "/policy/receiveJson/insurePolicy";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("order", orderDto);
            jsonObject.put("insureds", insuredsDtoList);
            String resultJson = null;
            System.out.println("发送保单信息---->" + jsonObject.toString());
            try {
                resultJson = HttpRequest.sendHttpPostJson(url, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
                modifyPolicyRecordStatus(info.getOrderNo(), info.getOrderNoIndex(), INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_EXIST_ERR, "网络异常", opUser);
                continue;
            }
            System.out.println("投保报文---->" + resultJson);
            if (resultJson == null) {
                modifyPolicyRecordStatus(info.getOrderNo(), info.getOrderNoIndex(), INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_EXIST_ERR, "未响应数据", opUser);
//                return;
            } else {
                JSONObject object = JSONObject.parseObject(resultJson);
                if (object.get("status") == null || ValidateUtil.isNull(object.get("status")) || Integer.parseInt(object.get("status").toString()) != 1) {
                    // 信息校验失败
                    modifyPolicyRecordStatus(info.getOrderNo(), info.getOrderNoIndex(), INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_EXIST_ERR, object.get("error") == null ? "" : object.get("error").toString(), opUser);
                } else {
                    // 投保处理中
                    modifyPolicyRecordStatus(info.getOrderNo(), info.getOrderNoIndex(), INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_DEALING, null, opUser);
//                    return;
                }
            }
        }
        // 2. 修改本地订单信息
        modifyOrderPolicyStatus(orderNo);
    }

    private void modifyPolicyRecordStatus(String orderNo, String orderNoIndex, Integer status, String reason, String opUser) {
        String sql = "update " + PojoTables.ORDER_POLICY_RECORD + " set status = " + status + " ,updateUser ='" + opUser + "'";
        if (ValidateUtil.isNotNull(reason)) {
            sql += " ,reason ='" + reason + "' ";
        }
        sql += " where delFlag = 0 and status!= " + status + " and orderNoIndex = '" + orderNoIndex + "'";
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        OrderPolicyRecordMemory.getInstance().addOrModify(orderNo);
    }

    // 修改订单上的保单信息状态
    public void modifyOrderPolicyStatus(String orderNo) {
        String selectSql = "select orderNoIndex,status from " + PojoTables.ORDER_POLICY_RECORD + " where orderNO = '" + orderNo + "' and delFlag = 0";
        List<PolicyInfo> list = null;
        try {
            list = (List<PolicyInfo>) UserDaoSql.getInstance().list(PolicyInfo.class, selectSql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Set<Integer> status = new HashSet<>();
        if (ValidateUtil.isAbsList(list)) {
            for (PolicyInfo info : list) {
                status.add(info.getStatus());
            }
            String updateSql = "update " + PojoTables.OrderInfo + " set ";
            if (status.size() == 1) {
                updateSql += " insuranceStatus = " + status.iterator().next();
            } else {
                updateSql += " insuranceStatus = " + INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_EXIST_ERR;
            }
            updateSql += " where orderNo = '" + orderNo + "' and delFlag = 0";
            try {
                UserDaoSql.getInstance().executeBySql(updateSql.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            OrderInfoMemory.getInstance().modifyStatus(orderNo);
        }
    }


//    // 保存保单本系统中 --团保
//    private void saveInsurancePolicy(List<PolicyInfo> policyInfos, PolicyInfo policyInfo, Long createTime, Connection con) throws SQLException {
//        int index = 0;
//        for (PolicyInfo tmpInfo : policyInfos) {
//            tmpInfo.setOrderNo(policyInfo.getOrderNo()).setOrderNoIndex(policyInfo.getOrderNo() + "_" + index).setDelFlag(0).setCreateTime(createTime).setCreateUser(policyInfo.getCreateUser());
//            tmpInfo.setOrderName(policyInfo.getOrderName()).setOrderMobile(policyInfo.getOrderMobile()).setOrderCardNum(policyInfo.getOrderCardNum()).setPrice(policyInfo.getPrice())
//                    .setStatus(1).setIsCancel(0).setType(policyInfo.getType()).setCode(policyInfo.getCode()).setBeginDate(policyInfo.getBeginDate()).setEndDate(policyInfo.getEndDate());
//            UserDaoSql.getInstance().saveObj(PojoTables.ORDER_POLICY_RECORD, tmpInfo, con);
//        }
//    }
//
//    // 发送保单信息
//    private void sendThreadPolicy(List<PolicyInfo> policyInfos, PolicyInfo policyInfo) throws Exception {
//        // 发送的保单信息
//        PolicyDto policyDto = new PolicyDto();
//        PolicyOrderDto orderDto = new PolicyOrderDto();
//        BeanUtils.copyProperties(policyInfo, orderDto);
//        orderDto.setMobile(policyInfo.getOrderMobile());
//        policyDto.setOrder(orderDto);
//        List<InsuredsDto> insuredsDtoList = new ArrayList<>();
//        for (PolicyInfo info : policyInfos) {
//            InsuredsDto insuredsDto = new InsuredsDto();
//            BeanUtils.copyProperties(info, insuredsDto);
//            insuredsDtoList.add(insuredsDto);
//        }
//        policyDto.setInsureds(insuredsDtoList);
////        String url = "http://127.0.0.1:16630/jytools/policy/receiveJson/insurePolicy";
//        String url = SYS_CONFIG_PATH.BAO_XIAN_SERVICE_URL + "/policy/receiveJson/insurePolicy";
////        String url = "http://o2otools.waimai101.com/jytools/policy/receiveJson/insurePolicy";
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("order", orderDto);
//        jsonObject.put("insureds", insuredsDtoList);
//        String resultJson = HttpRequest.sendHttpPostJson(url, jsonObject);
//        System.out.println("投保报文---->" + resultJson);
//        if (resultJson == null) {
//            throw new Exception("投保服务器未响应");
//        }
//        JSONObject object = JSONObject.parseObject(resultJson);
//        if (object.get("status") == null || ValidateUtil.isNull(object.get("status")) || Integer.parseInt(object.get("status").toString()) != 1) {
//            throw new Exception(object.get("error") == null ? "" : object.get("error").toString());
//        }
//    }

    // 更新收货地址记录次数
    public void updateReceivingAddressUsageTimes(Long toAddressId, Integer count) {
        String updateAddressSql = "update " + PojoTables.USER_ADDRESS_RECORD + " set usageTimes = usageTimes + " + count + " where id = " + toAddressId + " and delFlag = 0";
        try {
            UserDaoSql.getInstance().executeBySql(updateAddressSql);
        } catch (Exception e) {
            e.getMessage();
        }
        UserAddressRecordMemory.getInstance().modifyUserAddress(toAddressId);
    }

    /**
     * 保存收货地址记录
     *
     * @param prov
     * @param city
     * @param county
     * @param address
     * @param address2
     * @param address3
     * @param lat
     * @param lng
     * @param username
     * @param mobile
     */
    public void saveReceivingAddressRecord(String prov, String city, String county, String address, String address2, String address3, Double lat, Double lng, String username, String buyer, String mobile) {
        UserAddressRecord record = new UserAddressRecord();
        record.setCreateTime(DateUtils.getCurrTime());
        record.setCreateUser(username).setUsername(username).setDelFlag(0).setUsageTimes(0L);
        record.setProvince(prov);
        record.setCity(city);
        record.setCounty(county);
        record.setAddress(address);
        record.setAddress2(address2);
        record.setAddress3(address3);
        record.setLat(lat);
        record.setLng(lng);
        record.setBuyer(buyer);
        record.setTelephone(mobile);
        try {
            UserDaoSql.getInstance().saveObj(PojoTables.USER_ADDRESS_RECORD, record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserAddressRecordMemory.getInstance().addUserAddress(username);
    }
}
